package com.example.munidingwei

import android.app.Application
import android.util.Log
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer

class MainApplication : Application() {
    
    companion object {
        // 全局单例LocationService，确保即使应用退到后台也能持续运行
        private var locationServiceInstance: LocationService? = null
        
        // 全局单例BackendClient，用于与后台服务器通信
        private var backendClientInstance: BackendClient? = null
        
        fun getLocationService(context: android.content.Context): LocationService {
            if (locationServiceInstance == null) {
                locationServiceInstance = LocationService(context.applicationContext)
                Log.d("MainApplication", "创建全局LocationService实例")
            }
            return locationServiceInstance!!
        }
        
        fun getBackendClient(context: android.content.Context): BackendClient {
            if (backendClientInstance == null) {
                backendClientInstance = BackendClient(context.applicationContext)
                Log.d("MainApplication", "创建全局BackendClient实例")
            }
            return backendClientInstance!!
        }
    }
    
    override fun onCreate() {
        super.onCreate()
        
        Log.d("MainApplication", "========================================")
        Log.d("MainApplication", "🚀 应用启动")
        Log.d("MainApplication", "========================================")
        
        // 在Application中初始化百度地图SDK（确保最早执行）
        try {
            SDKInitializer.setAgreePrivacy(applicationContext, true)
            SDKInitializer.initialize(applicationContext)
            SDKInitializer.setCoordType(CoordType.BD09LL)
            Log.d("MainApplication", "✅ 百度地图SDK初始化成功")
        } catch (e: Exception) {
            Log.e("MainApplication", "❌ 百度地图SDK初始化失败", e)
        }
        
        // 预创建LocationService实例，确保生命周期与Application相同
        getLocationService(this)
        Log.d("MainApplication", "✅ LocationService已初始化")
        
        // 初始化BackendClient并设置默认服务器地址
        val backendClient = getBackendClient(this)
        
        // 从SharedPreferences读取保存的服务器地址
        val prefs = getSharedPreferences("app_prefs", MODE_PRIVATE)
        val savedUrl = prefs.getString("server_url", "https://myedu.webn.cc/backend-php/api.php")
        
        if (savedUrl != null) {
            backendClient.setServerUrl(savedUrl)
            Log.d("MainApplication", "✅ BackendClient已初始化，服务器地址: $savedUrl")
        }
        
        Log.d("MainApplication", "========================================")
        Log.d("MainApplication", "💡 ViewModel初始化后将自动连接到服务器")
        Log.d("MainApplication", "========================================")
    }
}

